<template>
	<view>
		<add-tip :tip="tip" :duration="duration" />
		<u-modal
			style="z-index: 999;"
			v-model="showLoginModal"
			:show-cancel-button="true"
			@confirm="confirmLogin"
			ref="uModal"
			content="还未登录, 登录才可以使用全部功能哦~"
			confirm-text="登录"
			:async-close="true"
		></u-modal>
		<u-toast ref="uToast" />
	</view>
</template>

<script>
import addTip from '@/components/uni-add-tips/uni-add-tips';
export default {
	data() {
		return {
			tip: '点击"添加小程序"，下次访问更便携',
			duration: 1,
			showLoginModal: false,
			userInfo: {}
		};
	},
	components: {
		addTip
	},
	onLoad() {
		this.userInfo = uni.getStorageSync('userInfo');
		if (!this.userInfo) {
			this.showLoginModal = true;
		}
	},
	methods: {
		confirmLogin() {
			uni.getUserProfile({
				desc: '登录',
				success: result => {
					uni.login({
						provider: 'weixin',
						success: res => {
							console.log(res.code);
							this.login(res.code, result.userInfo);
						}
					});
				},
				fail: err => {
					this.$refs.uToast.show({
						title: '你取消了授权，登录失败',
						type: 'error',
						position: 'top'
					});
					this.showLoginModal = false;
				}
			});
		},
		login(code, userInfo) {
			this.$api.wxLogin({
				data: {
					code
				},
				success: res => {
					if (parseInt(res.data.code) == 200) {
						userInfo.token = res.data.data.token;
						userInfo.id = res.data.data.id;
						this.$refs.uToast.show({
							title: '登录成功',
							type: 'success'
						});
						uni.setStorageSync('userInfo', userInfo);
						this.$api.syncUserInfo({
							data: userInfo,
							header: {
								json: true
							},
							success: res => {
								userInfo.lastVisitTime = res.data.data.lastVisitTime;
								userInfo.createTime = res.data.data.createTime;
								userInfo.openid = res.data.data.openid;
								uni.setStorageSync('userInfo', userInfo);
							},
							complete: () => {}
						});
						this.showLoginModal = false;
					} else {
						this.$refs.uToast.show({
							title: res.data.msg,
							type: 'error'
						});
					}
				},
				complete: data => {}
			});
		}
	}
};
</script>

<style scoped></style>
